const router = require('koa-router')();
const {db, QueryTypes} = require('../models/db')
const tool = require("../tools/tool");
const biz = require("../tools/biz");

router.post('/bf/arrived', async ctx => {
    let formData = ctx.request.body.formData
    let uid = ctx.user.id
    let tid = ctx.user.tenantId
    formData.tenantId = tid
    formData.salesId = uid
    formData.cby = uid
    formData.arrived = tool.getTime()
    formData.ctime = tool.getTime()
    formData.billDate = tool.getDay()
    formData.state = '未离店'
    let contact = await db.models['contact'].findOne({
        where: {
            id: formData.buId
        }
    })
    if (!contact) {
        return ctx.err('此客户不存在或已被删除')
    }
    // 到店自动离店上一家
    try {
        db.models['contactBfSets'].findOne({
            where: {
                tenantId: ctx.user.tenantId
            }
        }).then(ret => {
            if(ret && ret.autoLeft === '是') {
                db.models['contactBf'].findOne({
                    where: {
                        tenantId: tid,
                        salesId: uid,
                        state: '未离店'
                    },
                    order: [
                        ['id', 'desc']
                    ],
                    attributes: ['id', 'arrived']
                }).then(last => {
                    if(last) {
                        tool.leftShop(last.id, 1)
                    }
                })
            }
            // if(last && last.arrived) {
            //     // 没有照片
            //     let photo = await db.models['contactBfPic'].count({
            //         where: {
            //             contactBfId: last.id
            //         }
            //     })
            //     if (photo > 0) {
            //         // 有照片自动离开
            //         await tool.leftShop(last.id, 1)
            //     }
            // }
        })
    }
    catch (e) {

    }
    let lastModel = await db.models['contactBf'].findOne({
        where: {
            billDate: tool.getDay(),
            salesId: uid
        },
        attributes: ['longitude', 'latitude'],
        order: [['id', 'desc']]
    })
    let ret = await db.transaction(async t => {
        if(lastModel) {
            formData.lastDistance = tool.getDistance(formData.longitude, formData.latitude, lastModel.longitude, lastModel.latitude)
        }
        delete formData.leftTime
        let rets = await db.models['contactBf'].create(formData, {transaction: t})
        contact.longitude = formData.longitude
        contact.latitude = formData.latitude
        contact.addressLocation = formData.address
        contact.lastBfDay = tool.getDay()

        await contact.save({transaction: t})
        return rets
    })
    try {
        let roomId = ctx.roomId
        if(roomId) {
            setTimeout(async () => {
                let list = await biz.todayUndone(ctx, tool.getDay())
                ctx.io.to(roomId).emit('serverUpdateUndone', list)
            }, 300)
        }
    } catch (e) {
    }
    return ctx.suc('', ret)
})
// 拜访轨迹
router.post('/bf/bfGj', async ctx => {
    let tid = ctx.user.tenantId
    let where = ctx.request.body.where
    let auth = tool.authSql(ctx)
    let authSql = ' contact_bf '
    if(auth) {
        authSql = ` (select * from contact_bf a inner join (${auth}) b on a.salesId=b.uid) `
    }
    let sql = ` select a.id,a.arrived,a.address,a.buId,a.billDate,a.duration,a.durationStr,a.lastDistance,a.latitude,a.longitude,a.state,
        a.autoLeft,b.name  buName,c.id salesId,c.name salesName  from ${authSql} a left join contact b on a.buId=b.id
    left join admin c on a.cby=c.id where a.tenantId=${tid} and a.longitude is not null and a.latitude is not null `
    if(where.length > 0) {
        sql += ' and ' + where.join(' and ')
    }
    let ret = await db.query(sql, {type: QueryTypes.SELECT})
    return ctx.suc('', ret)
})
// 拜访线路
router.post('/bf/bfLine', async ctx => {
    let tid = ctx.user.tenantId
    let sql = `
        select a.*,b.name salesName from area a left join admin b on a.salesId=b.id where a.tenantId=${tid} 
    `
    let ret = await tool.page(ctx, sql)
    return ret
})
// 拜访要操作的菜单功能
router.post('/bf/bfMenu', async ctx => {
    let menu = [
        {
            id: 1, name: '到店', icon: tool.getPicUrl('appicon/到店2.png').url
        },
        {
            id: 2, name: '拍门头', icon: tool.getPicUrl('appicon/手机拍照.png').url
        },
        {
            id: 3, name: '拍陈列', icon: tool.getPicUrl('appicon/拍陈列.png').url
        },
        // {
        //     id: 4, name: '兑奖', icon: tool.getPicUrl('appicon/兑奖3.png').url
        // },
        {
            id: 5, name: '离店', icon: tool.getPicUrl('appicon/退出.png').url
        }
    ]
    return ctx.suc('', menu)
})
// 拜访明细
router.post('/bf/bfMx', async ctx => {
    let tid = ctx.user.tenantId
    let sql = `select a.*,b.name  buName,c.name salesName,
       case when a.state='已完成' then 
       (case when a.autoLeft=0 then '' when a.autoLeft=1 then '自动' when a.autoLeft=2 then '系统' else '' end) else '' end leftOp  
from contact_bf a 
           left join contact b on a.buId=b.id 
               left join admin c on a.salesId=c.id  where a.tenantId=${tid} `
    let ret = await tool.page(ctx, sql)

    return ret
})
// 拜访记录
router.post('/bf/bfMy', async ctx => {
    let tid = ctx.user.tenantId
    let uid = ctx.user.id
    let sql = `select a.*,a.id bfId,b.name  buName,c.name salesName  from contact_bf a left join contact b on a.buId=b.id 
               left join admin c on a.salesId=c.id  where a.tenantId=${tid} and a.salesId=${uid} `
    let ret = await tool.page(ctx, sql)
    return ret
})
// 拜访附近客户
router.post('/bf/bfNearBy', async ctx => {
    let day = tool.getDay()
    let uid = ctx.user.id
    let tid = ctx.user.tenantId
    let longitude = ctx.request.body.longitude
    let latitude = ctx.request.body.latitude
    let sql = ''
    if(longitude && latitude) {
        sql = `select top 20 id buId,name,address,longitude,latitude,distance,arrived,bfId,billDate,leftTime,state, linkMobile,linkName,linkPhone from (
                        select a.*,b.arrived, b.id bfId,b.billDate,b.leftTime,isnull(b.state,'') state from (
                            SELECT longitude,latitude,id,name,address, linkMobile,linkName,linkPhone,
                            geography::Point(${latitude}, ${longitude}, 4326).STDistance(geography::Point(latitude,longitude, 4326)) as distance 
                            from contact where tenantId=${tid} and salesId=${uid} and isDel=0 and longitude <>'' and latitude<>''
                        ) a left join 
                        (SELECT buId, arrived,id,billDate,leftTime,state from contact_bf where billDate='${day}' and tenantId=${tid}) b 
                        on a.id=b.buId  
                    ) a where state<>'已完成' order by distance asc  `
    }
    else {
        sql = `select top 20 id buId,name,address,longitude,latitude,'' distance,arrived,bfId,billDate,leftTime,state,linkMobile,linkName,linkPhone from (
                    select *,b.arrived,b.id bfId,b.billDate,b.leftTime,isnull(b.state,'') state from (
                    SELECT longitude,latitude,id,name,address,linkMobile,linkName,linkPhone,
                    '' distance
                    from contact where tenantId=${tid} and salesId=${uid} and isDel=0 and longitude <>'' and latitude<>''
                    ) a left join (SELECT buId, arrived,id,billDate,leftTime,state from contact_bf where billDate='${day}' and tenantId=${tid}  ) b on a.id=b.buId  
                    ) a where  state<>'已完成'  order by distance asc  `
    }
    let ret = await db.query(sql, {type: QueryTypes.SELECT})
    ret.map(row => {
        if(row.distance) {
            row.distance = tool.xe.round(tool.xe.divide(row.distance, 1000), 2) + '公里'
        }
    })
    return ctx.suc('', ret)
})
// 手机我的拜访页面数据
router.post('/bf/bfPage', async ctx => {
    let lnglat = ctx.request.body.lnglat
    let tab = ctx.request.body.tab
    let subTab = ctx.request.body.subTab
    let tid = ctx.user.tenantId
    let uid = ctx.user.id;
    let today = tool.getDay('')
    // 今日完成的数量
    let doneNoModelSql = `select count(*) total from (select buId from contact_bf where salesId=${uid} and state='已完成' and billDate='${today}' group by buId ) a `
    const doneNoModel = await db.query(doneNoModelSql, {type: QueryTypes.SELECT, plain: true})
    let sql = ``
    // 今日任务
    if(tab === 1) {
        if (subTab === '已完成') {
            sql =`SELECT a.*,a.id bfId,b.name salesName,c.name buName 
                    from contact_bf a inner join contact c on a.buId=c.id and a.salesId=${uid} left join admin b on a.salesId=b.id
                    where billDate='${today}' and a.tenantId=${tid} and a.state='已完成' 
                    `
            ctx.request.body.order = 'order by id desc '
        }
        else if (subTab === '推荐') {
            sql = `
                select a.buId,b.name buName,c.name salesName,b.address,b.addressLocation,b.linkPhone,b.linkName,b.longitude,b.latitude from 
                (
                    SELECT max(id) id,buId FROM contact_bf where tenantId=${tid} and billDate='${tool.getDay('', -7)}' GROUP BY buId 
                ) a inner join contact b on a.buId=b.id inner join admin c on b.salesId=c.id  
            `
            ctx.request.body.order = ' ORDER BY a.id desc '
        }
        else if (subTab === '超7天未拜访') {
            let beg = tool.getDay('',-6)
            let end = tool.getDay('', )
            // 近7天我的有拜访的客户
            let bfsql = ` select buId from contact_bf where tenantId=${tid} and billDate between '${beg}' and '${end}' and salesId=${uid} group by buId `
            let allsql = `select buId from contact_bf where tenantId=${tid}  and salesId=${uid} and buid not in (${bfsql}) group by buId `
            sql =`select a.buId,b.name buName,c.name salesName,b.address,b.addressLocation,b.linkPhone,b.linkName,b.longitude,b.latitude   from (
                ${allsql}
            ) a inner join  contact b on a.buId=b.id and b.isDel=0 inner join admin c on b.salesId=c.id  `
            ctx.request.body.order = ' order by b.id desc '
        }
        else if (subTab === '从未拜访') {
            sql =`select a.id buId,a.name buName,b.name salesName,a.address,a.addressLocation,a.linkPhone,a.linkName,a.longitude,a.latitude
            from contact a  inner join admin b on a.salesId=b.id and a.isDel=0  and a.tenantId=${tid} and a.salesId=${uid} and a.id 
            not in (SELECT distinct buId from contact_bf where  tenantId=${tid} and salesId=${uid} )   `
            ctx.request.body.order = ' order by b.id desc '
        }
    }
    // 附近客户
    if(tab === 2) {
        if(lnglat && lnglat.length === 2) {
            // 附近客户
            sql = `select  id buId,name buName,address,longitude,latitude,distance,arrived,bfId,billDate,leftTime,state, linkMobile,linkName,linkPhone from (
                        select a.*,b.arrived, b.id bfId,b.billDate,b.leftTime,isnull(b.state,'') state from (
                            SELECT longitude,latitude,id,name,address, linkMobile,linkName,linkPhone,
                            geography::Point(${lnglat[1]}, ${lnglat[0]}, 4326).STDistance(geography::Point(latitude,longitude, 4326)) as distance
                            from contact where tenantId=${tid} and salesId=${uid} and isDel=0 and longitude <>'' and latitude<>''
                        ) a
                            left join
                        (SELECT buId, arrived,id,billDate,leftTime,state from contact_bf where billDate='${today}' and tenantId=${tid}) b on a.id=b.buId
                    ) a  `
            ctx.request.body.order = ' order by distance asc  '
        } else {
            return ctx.suc('', {list: [], doneNo: doneNoModel ? doneNoModel.total : 0})
        }
    }
    // 未离店
    if(tab === 3) {
        sql = `select b.name buName,b.linkMobile,b.linkPhone,b.linkName,a.id bfId,  ad.name salesName ,a.* 
                from contact_bf a inner join contact b on a.buId=b.id and a.tenantId=${tid} and a.salesId=${uid} and leftTime is null
                inner join admin ad on a.salesId=ad.id  `
        ctx.request.body.order = ' order by a.id desc  '
    }
    let rets = await tool.page(ctx, sql)
    let list = rets.data.list

    list.map(row => {
        if(row.distance) {
            row.distance = tool.xe.round(tool.xe.divide(row.distance, 1000), 2) + '公里'
        } else {
            if(row.longitude && row.latitude && lnglat && lnglat.length === 2) {
                row.distance = tool.getDistance(row.longitude, row.latitude, lnglat[0], lnglat[1])
            }
        }
    })
    return ctx.suc('', {list: list, total: rets.data.total, doneNo: doneNoModel ? doneNoModel.total : 0})
})
// 今日 拜访任务
router.post('/bf/bfToday', async ctx => {
    let tid = ctx.user.tenantId;
    let day = tool.getDay();
    let uid = ctx.user.id;
    let week = '周' + tool.dayjs().format("dd")
    let sql =`
				select a.id buId,a.name,a.address,a.longitude,a.latitude  ,b.arrived 
				from(
					    SELECT id,name,address,longitude,latitude from contact where tenantId=${tid} and salesId=${uid} and isDel=0 and 
					     areaId in (SELECT id from area where salesId=1 and bfDate='${week}')
					) a left join (SELECT buId,arrived from contact_bf where billDate='${day}' and tenantId=${tid}) b on a.id=b.buId
				where b.buId is null
			`
    let ret = await db.query(sql, {type: QueryTypes.SELECT})
    return ctx.suc('', ret)
})
// 到店 未离开的
router.post('/bf/bfUnDone', async ctx => {
    let tid = ctx.user.tenantId;
    let uid = ctx.user.id;
    let sql = `select a.arrived,b.name,b.linkMobile,b.linkPhone,b.linkName,a.id bfId,b.address ,a.state ,a.leftTime, a.billDate ,b.id buId 
                from contact_bf a inner join contact b on a.buId=b.id and a.tenantId=${tid} and a.salesId=${uid} and 
                   arrived is not null and leftTime is null `
    let ret = await db.query(sql, {type: QueryTypes.SELECT})
    return ctx.suc('', ret)
})
// 删除图片
router.post('/bf/delPhoto', async ctx => {
    let billId = ctx.request.body.billId
    let fileName = ctx.request.body.fileName
    if(!fileName) return  ctx.err('没有要删除的文件')
    if(billId) {
        await db.models['contactBfPic'].destroy({
            where: {
                contactBfId: billId,
                fileName: fileName
            }
        })
        return  ctx.suc('')
    }
    else {
        return ctx.err('查询数据失败')
    }
})
// 兑奖
router.post('/bf/dj', async ctx => {
    let billid = ctx.request.body.billid
    let jpList = ctx.request.body.jpList
    let tid = ctx.user.tenantId
    if(billid) {
        let djTime = tool.getTime()
        await db.transaction(async (t) => {
            if(jpList.length === 0) {
                // 删除兑奖信息
                await db.models['contactBf'].update({
                    djTime: null
                }, {
                    where: {
                        id: billid
                    }
                }, {transaction: t})
            }
            else {
                await db.models['contactBf'].update({
                    djTime: djTime
                }, {
                    where: {
                        id: billid
                    }
                }, {transaction: t})
            }

            if(jpList.length === 0) {
                await db.models['contactBfDj'].destroy({
                    where: {
                        contactBfId: billid
                    }
                }, {transaction: t})
            }
            else {
                let arr = []
                jpList.map(row => {
                    arr.push({
                        tenantId: tid,
                        contactBfId: billid,
                        goodsJpId: row.id,
                        goodsJpName: row.name,
                        qty: row.qty
                    })
                })
                await db.models['contactBfDj'].bulkCreate(arr, {
                    transaction: t
                })
            }
        })
        return  ctx.suc('', jpList.length === 0 ? null : djTime)
    }
    else {
        return ctx.err('奖品保存失败')
    }
})

// 根据ID取拜访数据
router.post('/bf/getBfById', async ctx => {
    let tid = ctx.user.tenantId
    let id = ctx.request.body.id
    let ret = await db.models['contactBf'].findOne({
        where: {
            id: id,
            tenantId: tid,
        }
    })
    // 门头图片
    let md = await db.models['contactBfPic'].findAll({
        where: {
            contactBfId: id,
            tenantId: tid,
        }
    })
    ret.mtPicList = []
    ret.clPicList = []
    let djList = await db.models['contactBfDj'].findAll({
        where: {
            contactBfId: id
        }
    })
    ret.djList = djList
    let contact = await db.models['contact'].findOne({
        where: {
            id: ret.buId
        },attributes: ['name', 'linkPhone']
    })
    ret.buName = contact.name
    ret.linkPhone = contact.linkPhone
    let sales = await db.models['admin'].findOne({
        where: {
            id: ret.salesId
        },attributes: ['name']
    })
    md.map(row => {
        row.url = tool.getPicUrl(row.fileName, `${sales.name}`, true)
        if(row.type === '门头') {
            ret.mtPicList.push(row)
        }
        if(row.type === '陈列') {
            ret.clPicList.push(row)
        }
    })
    ret.salesName = sales.name
    return ctx.suc('', ret)
})

// 电脑查看拜访详情
router.post('/bf/getBfDetail', async ctx => {
    let tid = ctx.user.tenantId
    let id = ctx.request.body.id
    let ret = await db.models['contactBf'].findOne({
        where: {
            id: id,
            tenantId: tid,
        }
    })
    // 门头图片
    let md = await db.models['contactBfPic'].findAll({
        where: {
            contactBfId: id,
            tenantId: tid,
        }
    })
    ret.mtPicList = []
    ret.clPicList = []

    let djList = await db.models['contactBfDj'].findAll({
        where: {
            contactBfId: id
        }
    })
    let contact = await db.models['contact'].findOne({
        where: {
            id: ret.buId
        },
        attributes: ['name']
    })
    if(!contact) return  ctx.err('客户不存在或已被删除')
    ret.djList = djList
    ret.buName = contact.name

    let sales = await db.models['admin'].findOne({
        where: {
            id: ret.salesId
        },attributes: ['name']
    })
    if(!sales) return  ctx.err('业务员不存在或已被删除')
    md.map(row => {
        row.url = tool.getPicUrl(row.fileName, sales.name, true)
        if(row.type === '门头') {
            ret.mtPicList.push(row)
        }
        if(row.type === '陈列') {
            ret.clPicList.push(row)
        }
    })
    ret.salesName = sales.name
    return ctx.suc('', ret)
})
// 离店
router.post('/bf/left', async ctx => {
    let id = ctx.request.body.id
    if(!id) return ctx.err('未找到数据')
    let ret = await tool.leftShop(id, 0)
    try {
        let roomId = ctx.roomId
        if(roomId) {
            setTimeout(async () => {
                let list = await biz.todayPh(ctx, tool.getDay())
                let list1 = await biz.todayUndone(ctx, tool.getDay())
                ctx.io.to(roomId).emit('serverUpdatePh', list)
                ctx.io.to(roomId).emit('serverUpdateUndone', list1)
            }, 300)
        }
    } catch (e) {
    }
    if(ret.stat) {
        ctx.suc('已离店', ret.data)
    }
    else {
        ctx.err(ret.data)
    }
})
// 拜访路线列表
router.post('/bf/line', async ctx => {
    let tenantId = ctx.user.tenantId
    let order = ' order by a.id desc '
    ctx.request.body.order = order
    const sql = `SELECT a.id,a.tenantId,a.name,a.salesId,ad.name salesName,a.bfDate,b.ters from area a
                  left join
                  (
                      select a.id, count(*) ters from area a
                      left join contact c on a.id=c.areaId
                      where a.tenantId=${tenantId}  and c.id is not null
                      GROUP BY  a.id
                  ) b on a.id=b.id
                  left join admin ad on a.salesId=ad.id
                  WHERE a.tenantId=${tenantId}  `
    return tool.page(ctx, sql)
})
router.post('/bf/phAdd', async ctx => {
    let where = ctx.request.body.where
    let tid = ctx.user.tenantId
    let sql1 = `select salesId,count(*) khs from contact where tenantId=${tid} and ${where.join(' and ')} group by salesId `
    let sql = `select a.salesId,a.khs,b.name salesName from (${sql1}) a left join admin b on a.salesId=b.id `
    let ret = await db.query(sql, {type:QueryTypes.SELECT})
    ctx.suc('', ret)
})
// 新客排行
router.post('/bf/phBf', async ctx => {
    let where = ctx.request.body.where
    let tid = ctx.user.tenantId
    let wh = ''
    if(where && where.length > 0) {
        wh = ` and ${where.join(' and ')} `
    }
    let sql1 = `select cby,count(*) bfTimes from contact_bf where tenantId=${tid} ${wh} group by cby `
    let sql2 = `select cby,count(*) buTimes from ( SELECT cby,buId,count(*) buTimes from contact_bf where tenantId=${tid} ${wh} GROUP BY cby,buId ) as a GROUP BY cby `
    let sql = `select a.cby,c.name salesName,a.bfTimes,b.buTimes from (${sql1}) a left join (${sql2}) b on a.cby=b.cby left join admin c on a.cby=c.id order by a.bfTimes desc `
    let ret = await db.query(sql, {type:QueryTypes.SELECT})
    ret.map(row => {
        row.avgTimes = tool.xe.round(tool.xe.divide(row.bfTimes, row.buTimes), 1)
    })
    ctx.suc('', ret)
})
router.post('/bf/takePhoto', async ctx => {
    let billId = ctx.request.body.billId
    let fileName = ctx.request.body.fileName
    let type = ctx.request.body.type
    if(billId) {
        // let picUrl = tool.getPicUrl(fileName)
        // let picShopTime = tool.getTime()
        let mod = {
            tenantId: ctx.user.tenantId,
            fileName: fileName,
            contactBfId: billId,
            type: type,
            cby: ctx.user.id,
            ctime: tool.getTime()
        }
        await db.models['contactBfPic'].create(mod)
        return  ctx.suc('')
    }
    else {
        return ctx.err('查询数据失败')
    }
})

module.exports = router;
